// 确保在DOM加载完成后执行Vue应用初始化
document.addEventListener('DOMContentLoaded', function() {
    const { createApp, ref, onMounted } = Vue;

    const app = createApp({
    setup() {
        // 响应式数据
        const query = ref('');
        const rerank = ref(false);
        const category = ref('default');
        const categories = ref([]);
        const results = ref([]);
        const resultCount = ref(0);
        const loading = ref(false);
        const errorMessage = ref('');
        const showError = ref(false);
        const showResults = ref(false);

        // 加载分类列表
        const loadCategories = () => {
            fetch('/get_category')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.category_list && data.category_list.length > 0) {
                        categories.value = data.category_list;
                        // 查找默认分类
                        const defaultCategory = data.category_list.find(cat => cat.name === 'default');
                        if (defaultCategory) {
                            category.value = defaultCategory.name;
                        } else if (data.category_list.length > 0) {
                            category.value = data.category_list[0].name;
                        }
                    }
                })
                .catch(error => {
                    console.error('加载分类列表失败:', error);
                    errorMessage.value = '加载分类列表失败';
                    showError.value = true;
                });
        };

        // 处理查询提交
        const handleSubmit = (e) => {
            e.preventDefault();
            if (!query.value.trim()) return;

            loading.value = true;
            showError.value = false;
            showResults.value = false;

            const queryData = {
                query: query.value.trim(),
                top_k: 5,
                rerank: rerank.value,
                category: category.value
            };

            // 获取开始时间
            const start = performance.now();

            fetch('/query', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(queryData)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error(errorData.detail || errorData.message || `HTTP错误: ${response.status} ${response.statusText}`);
                    }).catch(() => {
                        throw new Error(`网络响应错误: ${response.status} ${response.statusText}`);
                    });
                }
                return response.json();
            })
            .then(data => {
                loading.value = false;

                if (data.success) {
                    // 获取结束时间
                    const end = performance.now();
                    const duration = ((end - start) / 1000).toFixed(1);
                    resultCount.value = `找到 ${data.results.length} 个结果, 耗时 ${duration} 秒`;
                    results.value = data.results;
                    showResults.value = true;
                } else {
                    errorMessage.value = data.message || '查询失败，请稍后重试';
                    showError.value = true;
                    showResults.value = true;
                }
            })
            .catch(error => {
                loading.value = false;
                errorMessage.value = error.message || '查询过程中发生错误';
                showError.value = true;
                showResults.value = true;
                console.error('查询错误:', error);
            });
        };

        // 设置Ctrl+Enter提交
        const setupCtrlEnterSubmit = () => {
            const queryInput = document.getElementById('query');
            if (!queryInput) return;

            queryInput.addEventListener('keydown', function(e) {
                if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                    e.preventDefault();
                    handleSubmit(e);
                } else if (e.key === 'Enter') {
                    e.preventDefault();
                    handleSubmit(e);
                }
            });
        };

        // 添加导航栏滚动效果
        const setupScrollEffects = () => {
            const navbar = document.querySelector('nav');
            if (!navbar) return;

            window.addEventListener('scroll', function() {
                if (window.scrollY > 10) {
                    navbar.classList.add('bg-white/95', 'backdrop-blur-sm');
                } else {
                    navbar.classList.remove('bg-white/95', 'backdrop-blur-sm');
                }
            });
        };

        // 页面加载完成后初始化
        onMounted(() => {
            loadCategories();
            setupCtrlEnterSubmit();
            setupScrollEffects();

            // 平滑滚动效果
            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function (e) {
                    e.preventDefault();
                    document.querySelector(this.getAttribute('href'))?.scrollIntoView({
                        behavior: 'smooth'
                    });
                });
            });
        });

        // 导出供模板使用的数据和方法
        return {
            query,
            rerank,
            category,
            categories,
            results,
            resultCount,
            loading,
            errorMessage,
            showError,
            showResults,
            handleSubmit
        };
    }
    });

    app.mount('#app');
});